<?php
/*=====================================================================
  (C)2007 BeaBo Japan by Hiroki Seike
  http://beabo.net/
=====================================================================*/

// --------------------------------------------------------
// Tag Service
// --------------------------------------------------------
if (!defined('XOOPS_ROOT_PATH')) exit();

class TagService {

	// OR search ( single tag )
	function getTagBookmarks($searchTagsArray, $viewStart = 0, $viewCount = 5) 
	{
		$retArray = array();
		$bookmarkTagArray = array();

		$root =& XCube_Root::getSingleton();
		$db =& $root->mController->mDB;

		$tagHandler = xoops_getmodulehandler('tags');

		$sql = 'SELECT DISTINCT p.bId, uId, bModified, bTitle, bAddress, bDescription, bAddress, image FROM '. $db->prefix("scuttle_bookmarks")
			.' p LEFT JOIN '. $db->prefix("scuttle_tags").' c ON p.bId = c.bId';
			if (is_array($searchTagsArray) && $count = count($searchTagsArray)) {
				$sql .= " WHERE (c.tag = '$searchTagsArray[0]')";
				for($i = 1;$i < $count;$i++) {
					$sql .= " OR (c.tag = '$searchTagsArray[$i]')";
				}
			} 
		$sql .= ' ORDER BY p.bModified DESC';
		$result = $db->query($sql, $viewCount ,$viewStart);
		while (list($bId, $uId, $bModified, $bTitle, $bAddress, $bDescription, $bAddress, $image) = $db -> fetchRow($result)) {
			$bookmarkGetTagArray = $tagHandler->getEntoryTagArray($bId);

			// chenge bookmark tag to array.
			// array pattern same AND search patttern
			foreach ($bookmarkGetTagArray as $bookmarkTag) {
				$tagsArray['tagword'] = $bookmarkTag;
				if (in_array($bookmarkTag, $searchTagsArray)) {
					$tagsArray['is_serch_tag'] =  true;    // bookmark tag is serch tag.
				} else {
					$tagsArray['is_serch_tag'] =  false;
				}
				$bookmarkTagArray[] =& $tagsArray;
				unset($tagsArray);
			}
			array_push($retArray, array(
				'bId'          => $bId,
				'uId'          => $uId,
				'bModified'    => $bModified,
				'bTitle'       => $bTitle,
				'bAddress'     => $bAddress,
				'bDescription' => $bDescription,
				'bAddress'     => $bAddress,
				'tag_array'    => $bookmarkTagArray,
				'image'        => $image,
				'hatena'       => addHatenaUsers($bAddress), // get hatena bookmarks

			));
			unset($bookmarkTagArray);
		}
		return $retArray;
	}

	// OR count ( single tag )
	function getTagBookmarksCount($searchTagsArray) 
	{
		$retArray = array();
		$root =& XCube_Root::getSingleton();
		$db =& $root->mController->mDB;

		$sql = 'SELECT DISTINCT p.bId, uId, bModified, bTitle, bAddress, bDescription, bAddress FROM '. $db->prefix("scuttle_bookmarks")
			.' p LEFT JOIN '. $db->prefix("scuttle_tags").' c ON p.bId = c.bId';
			if (is_array($searchTagsArray) && $count = count($searchTagsArray)) {
				$sql .= " WHERE (c.tag = '$searchTagsArray[0]')";
				for($i = 1;$i < $count;$i++) {
					$sql .= " OR (c.tag = '$searchTagsArray[$i]')";
				}
			} 
		$sql .= ' ';
		$result = $db->query($sql);
		return $db->getRowsNum($result); 
	}

	// AND search ( Some tags )
	function getTagBookmarksAnd($searchTagsArray, $viewStart = 0, $viewCount=5) 
	{
		$countTag = count($searchTagsArray);

		$retArray = array();
		$tagsArray = array();
		$bookmarkTagArray = array();

		$root =& XCube_Root::getSingleton();
		$db =& $root->mController->mDB;
		$tagHandler = xoops_getmodulehandler('tags');

		$sql = 'SELECT p.bId, uId, bModified, bTitle, bAddress, bDescription, bAddress, image FROM '
			. $db->prefix("scuttle_bookmarks"). ' p,'. $db->prefix("scuttle_tags").' c WHERE p.bId = c.bId AND (c.tag IN (';
			if (is_array($searchTagsArray) && $count = count($searchTagsArray)) {
				$sql .= "'$searchTagsArray[0]'";
				for($i = 1;$i < $count;$i++) {
					$sql .= " , '$searchTagsArray[$i]'";
				}
			} 
		$sql .= ')) GROUP BY p.bId HAVING COUNT( p.bId )='. $countTag. ' ORDER BY p.bModified DESC';
		$result = $db->query($sql, $viewCount ,$viewStart);
		while (list($bId, $uId, $bModified, $bTitle, $bAddress, $bDescription, $bAddress, $image) = $db -> fetchRow($result)) {
			// get bookmark tags
			$bookmarkGetTagArray = $tagHandler->getEntoryTagArray($bId);
			// chack bookmark tag for serch tag.
			foreach ($bookmarkGetTagArray as $bookmarkTag) {
				$tagsArray['tagword'] = $bookmarkTag;
				if (in_array($bookmarkTag, $searchTagsArray,true)) {
					$tagsArray['is_serch_tag'] =  true;    // bookmark tag is serch tag.
				} else {
					$tagsArray['is_serch_tag'] =  false;
				}
				$tagLinkCount = 0;
				$tagLink = "";
				foreach ($searchTagsArray as $searchTag) {
					if ($searchTag <> $bookmarkTag) {
						if ($tagLinkCount == 0) {
							$tagLink = $searchTag;
							$tagLinkCount++;
						} else {
							$tagLink = $tagLink .'--'.$searchTag;
						}
					}
				}
				$tagsArray['tag_link'] = $tagLink;
				$bookmarkTagArray[] =& $tagsArray;
				unset($tagsArray);
			}
			array_push($retArray, array(
				'bId'          => $bId,
				'uId'          => $uId,
				'bModified'    => $bModified,
				'bTitle'       => $bTitle,
				'bAddress'     => $bAddress,
				'bDescription' => $bDescription,
				'bAddress'     => $bAddress,
				'tag_array'    => $bookmarkTagArray,
				'image'        => $image,
				'hatena'       => addHatenaUsers($bAddress), // get hatena bookmarks
			));
			unset($bookmarkTagArray);
		}
		return $retArray;
	}

	// AND count ( Some tags )
	function getTagBookmarksAndCount($searchTagsArray) 
	{
		$countTag = count($searchTagsArray);
		$root =& XCube_Root::getSingleton();
		$db =& $root->mController->mDB;
		$tagHandler = xoops_getmodulehandler('tags');
		$sql = 'SELECT p.bId, uId, bModified, bTitle, bAddress, bDescription, bAddress, image FROM '
			. $db->prefix("scuttle_bookmarks"). ' p,'. $db->prefix("scuttle_tags").' c WHERE p.bId = c.bId AND (c.tag IN (';
			if (is_array($searchTagsArray) && $count = count($searchTagsArray)) {
				$sql .= "'$searchTagsArray[0]'";
				for($i = 1;$i < $count;$i++) {
					$sql .= " , '$searchTagsArray[$i]'";
				}
			} 
		$sql .= ')) GROUP BY p.bId HAVING COUNT( p.bId )='. $countTag. ' ORDER BY p.bModified ASC';
		$result = $db->query($sql);
		return $db->getRowsNum($result); 
	}

	function &getAllTags($days = NULL) {
		$root =& XCube_Root::getSingleton();
		$db =& $root->mController->mDB;

		if (is_null($days) || !is_int($days)) {
			$span = '';
		} else {
			$span = ' AND W.submited > "'. time() - (86400 * $days) .'"';
		}
		$sql = 'SELECT T.tag, COUNT(T.id) AS bCount FROM '.$db -> prefix("scuttle_tags").' AS T, '. $db -> prefix("scuttle_bookmarks") .' AS W WHERE ';
		$sql .= 'W.bId = T.bId AND W.bStatus < 2';
		$sql .= $span .'  GROUP BY T.tag ORDER BY tag';
		$tags =& $db -> query($sql) ;
		$tagArray = array();
		while (list($tag, $count) = $db -> fetchRow($tags)) {
			array_push($tagArray, array(
				'tag'  => addSlashes($tag),
				'count' => intval($count),
			));
		}
		return $tagArray ;
	}


	// --------------------------------------------------------
	// get popular tags
	// --------------------------------------------------------
	function &getPopularTags($limit = 30, $days = NULL) {
		$root =& XCube_Root::getSingleton();
		$db =& $root->mController->mDB;
	
		if (is_null($days) || !is_int($days)) {
			$span = '';
		} else {
			$span = ' AND W.submited > "'. time() - (86400 * $days) .'"';
		}
		$sql = 'SELECT T.tag, COUNT(T.id) AS bCount FROM '.$db -> prefix("scuttle_tags").' AS T, '. $db -> prefix("scuttle_bookmarks") .' AS W WHERE ';
		$sql .= 'W.bId = T.bId ';
		$sql .= $span .'  GROUP BY T.tag ORDER BY bCount DESC, tag';
		$tags =& $db -> query($sql, $limit) ;
		$tagArray = array();
		while (list($tag, $count) = $db -> fetchRow($tags)) {
			array_push($tagArray, array(
				'tag'  => addSlashes($tag),
				'count' => intval($count),
			));
		}
		return $tagArray ;
	}

	// --------------------------------------------------------
	// change font size to tag Cloud
	// --------------------------------------------------------
	function tagCloud($tags = NULL, $steps = 5, $sizemin = 1, $sizemax = 6, $sortOrder = 'alphabet_asc') {
	
		if (is_null($tags) || count($tags) < 1) {
			return false;
		} 
	
		// $tags is original sort array
		$sortCountTags = $tags;
	
		// sort count
		foreach($sortCountTags as $value){
			$uesdcount[] = $value['count'];
		}
		array_multisort($uesdcount,SORT_DESC,SORT_NUMERIC, $sortCountTags);
	
		// count min $ max
		$min = $sortCountTags[count($sortCountTags) - 1]['count'];
		$max = $sortCountTags[0]['count'];
	
	
		for ($i = 1; $i <= $steps; $i++) {
			$delta = ($max - $min) / (2 * $steps - $i);
			$limit[$i] = $i * $delta + $min;
		} 
		$sizestep = ($sizemax - $sizemin) / $steps;
	
		foreach ($tags as $row) {
			$next = false;
			for ($i = 1; $i <= $steps; $i++) {
				if (!$next && $row['count'] <= $limit[$i]) {
					$size = $sizestep * ($i - 1) + $sizemin;
					$next = true;
				} 
			} 
			$tempArray = array('size' => $size . '%');
			$row = array_merge($row, $tempArray);
			$output[] = $row;
		} 

		if ($sortOrder == 'alphabet_desc') {
			rsort($output);
		} else {
			sort($output);
		}
		return $output ;
	}
}



?>